package controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.hadoop.util.Time;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;

import com.alibaba.fastjson.JSONObject;

import beans.*;
//import engine.BIEngine0_0_1.TaskThread;
//import engine.BIEngine0_0_1.ParseTaskJson;
//import engine.BIEngine0_0_2.ParseTaskJson;
//import engine.BIEngine0_0_2.TaskThread;
import engine.BIEngine0_1.InitJobStateThread;
import net.TaskOperator;
import portal.controller.BaseServlet;
import utils.Log4jInit;
import utils.Time2Str;
import utils.UserLogUtil;

/**
 * Servlet implementation class StartTask
 */
//@Scope("prototype")
public class StartTask extends BaseServlet {
	private static final long serialVersionUID = 1L;
	@Autowired
	TaskOperator taskOperator;
	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public StartTask() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//获取userId
		//Time2Str.printCurrentTime("start task");
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
		Log4jInit.logger.info("-------START TASK TIME : " + sf.format(new Date()));
		String userId = (String) request.getSession().getAttribute("userId");
		String taskId = request.getParameter("taskId");
		String taskHash = request.getParameter("taskHash");
//		String inputs = request.getParameter("inputs");
		JSONObject result = new JSONObject();
		if ((taskId != null) && (taskHash != null)) {
			Log4jInit.logger.info(taskId +" "+taskHash);
			result = taskOperator.startTask(taskId,taskHash);
			response.getWriter().write(result.toString());
			//Time2Str.printCurrentTime("start task response");
			// 日志记录
			UserLogUtil.dbLog(LogEnum.historyTask, LogEnum.startHistoryTask,
					userId, LogEnum.task.getValue()+"编号："+taskId+"，"+LogEnum.historyTask.getValue()+"哈希值："+taskHash);
			//任务启动后，更新作业部分信息
			new InitJobStateThread(taskHash).start();
		} else {
			result.put("message", "接收到的任务标识为空");
			result.put("result", false);
			response.getWriter().write(result.toString());
		}

	}
}
